package cn.zl.ymcc.config;

import cn.zl.ymcc.constant.MqConstant;
import cn.zl.ymcc.mq.OrderTransactionListener;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class RocketMQManualConfig {


    private String nameServer="localhost:9876";

    /**
     * 事务消息生产者
     */
    @Bean(name = "transactionMQProducer")
    public TransactionMQProducer transactionMQProducer(OrderTransactionListener orderTransactionListener) {
        try {
            TransactionMQProducer producer = new TransactionMQProducer(MqConstant.MQ_COURSEORDER_PAY_GROUP_TRANSACTION);
            producer.setNamesrvAddr(nameServer);
            producer.setSendMsgTimeout(3000);
            // 设置重试次数
            producer.setRetryTimesWhenSendFailed(2);
            
            // 配置事务线程池
            ExecutorService executorService = new ThreadPoolExecutor(
                    2,
                    5,
                    100,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(2000),
                    r -> {
                        Thread thread = new Thread(r);
                        thread.setName("transaction-msg-check-thread");
                        return thread;
                    });
            
            producer.setExecutorService(executorService);
            
            // 手动设置事务监听器
            producer.setTransactionListener(orderTransactionListener);
            
            producer.start();
            System.out.println("事务消息生产者启动成功: tx-courseorder-pay-group");
            return producer;
        } catch (Exception e) {
            throw new RuntimeException("启动事务消息生产者失败", e);
        }
    }

    /**
     * 普通消息生产者
     */
    @Bean
    public DefaultMQProducer defaultMQProducer() {
        try {
            DefaultMQProducer producer = new DefaultMQProducer("default-producer-group");
            producer.setNamesrvAddr(nameServer);
            producer.setSendMsgTimeout(3000);
            producer.setRetryTimesWhenSendFailed(2);
            producer.start();
            System.out.println("普通消息生产者启动成功");
            return producer;
        } catch (Exception e) {
            throw new RuntimeException("启动普通消息生产者失败", e);
        }
    }
}